package com.dahaonetwork.smartfactory.constant;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dahaonetwork.smartfactory.util.ThreadLocalUtils;
import com.dahaonetwork.smartfactory.util.UserModelUtil;




//@Component
public class ThreadLocalInterceptor implements HandlerInterceptor{
	
	private Logger log = LoggerFactory.getLogger(this.getClass());
	public static final String SESSION = "session";
	
	public static final String REQUEST = "request";
	
	public static final String RESPONSE ="response";
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView mv)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		try {
			// usermodel相关的所有均需要将白名单拦截在门外，否则会造成死循环

			String user=UserModelUtil.getUserModel(request.getSession());
			
			HttpSession session =request.getSession();
			
			session.setAttribute("userModel", user);
			
			ThreadLocalUtils.setObjectToThreadLocal(SESSION, session);
			
			ThreadLocalUtils.setObjectToThreadLocal(REQUEST, request);
			
			ThreadLocalUtils.setObjectToThreadLocal(RESPONSE, response);
			return true;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			// TODO: handle exception
		}
		return true;
	}

}